package com.learn.redis.utils.idempotent;

import com.learn.redis.helper.RedisHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.UUID;


/**
 * @author PC
 */
@Component
public class DefaultIdempotentUtil implements Idempotent {
    private final static Logger logger = LoggerFactory.getLogger(DefaultIdempotentUtil.class);

    private final static String PREFIX = "token_%s_%s";

    public final static String DEFAULT_SERVERNAME = "default";

    public final static String UNIQUE_FLAG = "true";

    public RedisHelper redisHelper;


    @Autowired
    public void setRedisHelper(RedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }



    /**
     * 获取token的接口需要防止疯狂获取导致redis暴库
     *
     * @param serverName 服务名
     * @return token
     */
    public String createUniqueTokenWithServerName(String serverName) {
        serverName = Optional.ofNullable(serverName).orElse(DEFAULT_SERVERNAME);
        String uuid = UUID.randomUUID().toString();
        String uniqueToken = String.format(PREFIX, serverName, uuid);
        logger.debug("{} generate unique_token {}", serverName, uniqueToken);
        redisHelper.strSet(uniqueToken, UNIQUE_FLAG);
        return uniqueToken;
    }

    @Override
    public String createUniqueLockKey(String... args) {
         // 确保至少有一个参数被提供
        if (args == null || args.length == 0) {
            throw new IllegalArgumentException("At least one argument is required.");
        }

        // 使用第一个参数作为serverName
        return createUniqueTokenWithServerName(args[0]);
    }

    @Override
    public Boolean lockKeyExist(String lockKey){
        return StringUtils.isNotEmpty(redisHelper.strGet(lockKey));
    }

    @Override
    public Boolean clear(String lockKey) {
        return redisHelper.del(lockKey);
    }
}
